import { ref } from 'vue'
import { message } from 'ant-design-vue'

interface AnnouncementMessage {
  type: string
  message: string
  announcement?: any
}

class AnnouncementWebSocketService {
  private ws: WebSocket | null = null
  private reconnectTimer: number | null = null
  private heartbeatTimer: number | null = null
  private reconnectAttempts = 0
  private maxReconnectAttempts = 5
  private reconnectInterval = 3000
  
  // 响应式状态
  public connected = ref(false)
  public unreadCount = ref(0)
  
  // 事件回调
  private onNewAnnouncementCallback?: (announcement: any) => void
  private onUnreadCountChangeCallback?: (count: number) => void

  constructor() {
    this.connect()
  }

  private connect() {
    if (this.ws) {
      this.disconnect()
    }

    try {
      // 构建WebSocket URL（项目使用cookie认证，不需要token）
      const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:'
      // 使用固定的后端端口8123，而不是前端端口
      const wsUrl = `${protocol}//localhost:8123/api/ws/announcement`
      
      this.ws = new WebSocket(wsUrl)
      
      this.ws.onopen = () => {
        console.log('公告WebSocket连接成功')
        this.connected.value = true
        this.reconnectAttempts = 0
        this.startHeartbeat()
      }
      
      this.ws.onmessage = (event) => {
        try {
          const data: AnnouncementMessage = JSON.parse(event.data)
          this.handleMessage(data)
        } catch (error) {
          console.error('解析公告WebSocket消息失败:', error)
        }
      }
      
      this.ws.onclose = (event) => {
        console.log('公告WebSocket连接关闭:', event.code, event.reason)
        this.connected.value = false
        this.stopHeartbeat()
        
        // 如果不是主动关闭，尝试重连
        if (event.code !== 1000 && this.reconnectAttempts < this.maxReconnectAttempts) {
          this.scheduleReconnect()
        }
      }
      
      this.ws.onerror = (error) => {
        console.error('公告WebSocket连接错误:', error)
        this.connected.value = false
      }
      
    } catch (error) {
      console.error('创建公告WebSocket连接失败:', error)
    }
  }

  private handleMessage(data: AnnouncementMessage) {
    switch (data.type) {
      case 'NEW_ANNOUNCEMENT':
        message.success({
          content: `📢 ${data.message}`,
          duration: 5,
          style: {
            marginTop: '80px' // 避免被header遮挡
          }
        })
        
        if (data.announcement && this.onNewAnnouncementCallback) {
          this.onNewAnnouncementCallback(data.announcement)
        }
        
        // 增加未读数量
        this.unreadCount.value += 1
        if (this.onUnreadCountChangeCallback) {
          this.onUnreadCountChangeCallback(this.unreadCount.value)
        }
        break
        
      case 'UPDATE_ANNOUNCEMENT':
        message.info({
          content: `📝 ${data.message}`,
          duration: 3,
          style: {
            marginTop: '80px'
          }
        })
        break
        
      case 'DELETE_ANNOUNCEMENT':
        message.warning({
          content: `🗑️ ${data.message}`,
          duration: 3,
          style: {
            marginTop: '80px'
          }
        })
        break
        
      default:
        console.log('收到公告WebSocket消息:', data)
    }
  }

  private scheduleReconnect() {
    if (this.reconnectTimer) {
      clearTimeout(this.reconnectTimer)
    }
    
    this.reconnectAttempts++
    const delay = this.reconnectInterval * Math.pow(2, this.reconnectAttempts - 1)
    
    console.log(`将在 ${delay}ms 后尝试第 ${this.reconnectAttempts} 次重连`)
    
    this.reconnectTimer = window.setTimeout(() => {
      this.connect()
    }, delay)
  }

  private startHeartbeat() {
    this.heartbeatTimer = window.setInterval(() => {
      if (this.ws && this.ws.readyState === WebSocket.OPEN) {
        this.ws.send(JSON.stringify({ type: 'ping' }))
      }
    }, 30000) // 30秒心跳
  }

  private stopHeartbeat() {
    if (this.heartbeatTimer) {
      clearInterval(this.heartbeatTimer)
      this.heartbeatTimer = null
    }
  }

  public disconnect() {
    if (this.reconnectTimer) {
      clearTimeout(this.reconnectTimer)
      this.reconnectTimer = null
    }
    
    this.stopHeartbeat()
    
    if (this.ws) {
      this.ws.close(1000, '主动断开连接')
      this.ws = null
    }
    
    this.connected.value = false
  }

  public setUnreadCount(count: number) {
    this.unreadCount.value = count
  }

  public decreaseUnreadCount() {
    if (this.unreadCount.value > 0) {
      this.unreadCount.value -= 1
      if (this.onUnreadCountChangeCallback) {
        this.onUnreadCountChangeCallback(this.unreadCount.value)
      }
    }
  }

  public onNewAnnouncement(callback: (announcement: any) => void) {
    this.onNewAnnouncementCallback = callback
  }

  public onUnreadCountChange(callback: (count: number) => void) {
    this.onUnreadCountChangeCallback = callback
  }
}

// 创建全局单例
export const announcementWebSocket = new AnnouncementWebSocketService()

export default AnnouncementWebSocketService
